package com.kwdb.server.parser;

import com.kwdb.grpc.DataPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Line Protocol解析器
 */
public class LineProtocolParser {
    
    private static final Logger logger = LoggerFactory.getLogger(LineProtocolParser.class);
    
    /**
     * 解析Line Protocol格式字符串
     * 格式: measurement,tag1=value1,tag2=value2 field1=value1,field2=value2 timestamp
     */
    public DataPoint parse(String lineProtocol) {
        logger.debug("解析Line Protocol: {}", lineProtocol);
        
        // 简化实现：直接返回解析的DataPoint
        String[] parts = lineProtocol.split(" ");
        
        DataPoint.Builder builder = DataPoint.newBuilder();
        
        if (parts.length > 0) {
            // 解析measurement和tags
            String[] measurementAndTags = parts[0].split(",");
            if (measurementAndTags.length > 0) {
                builder.setMeasurement(measurementAndTags[0]);
            }
            
            // 解析tags
            for (int i = 1; i < measurementAndTags.length; i++) {
                String[] tag = measurementAndTags[i].split("=");
                if (tag.length == 2) {
                    builder.putTags(tag[0], tag[1]);
                }
            }
        }
        
        if (parts.length > 1) {
            // 解析fields
            String[] fields = parts[1].split(",");
            for (String field : fields) {
                String[] kv = field.split("=");
                if (kv.length == 2) {
                    builder.putFields(kv[0], kv[1]);
                }
            }
        }
        
        if (parts.length > 2) {
            // 解析timestamp
            try {
                long timestamp = Long.parseLong(parts[2]);
                builder.setTimestamp(timestamp);
            } catch (NumberFormatException e) {
                logger.warn("无效的时间戳: {}", parts[2]);
                builder.setTimestamp(System.currentTimeMillis());
            }
        } else {
            builder.setTimestamp(System.currentTimeMillis());
        }
        
        builder.setLineProtocol(lineProtocol);
        
        return builder.build();
    }
    
    /**
     * 将DataPoint转换为Line Protocol格式
     */
    public String toLineProtocol(DataPoint dataPoint) {
        StringBuilder sb = new StringBuilder();
        
        // measurement
        sb.append(dataPoint.getMeasurement());
        
        // tags
        if (dataPoint.getTagsCount() > 0) {
            dataPoint.getTagsMap().forEach((key, value) -> {
                sb.append(",").append(key).append("=").append(value);
            });
        }
        
        // fields
        if (dataPoint.getFieldsCount() > 0) {
            sb.append(" ");
            boolean first = true;
            for (java.util.Map.Entry<String, String> entry : dataPoint.getFieldsMap().entrySet()) {
                if (!first) sb.append(",");
                sb.append(entry.getKey()).append("=").append(entry.getValue());
                first = false;
            }
        }
        
        // timestamp
        if (dataPoint.getTimestamp() > 0) {
            sb.append(" ").append(dataPoint.getTimestamp());
        }
        
        return sb.toString();
    }
}

